package zack.project.infrastructure.persistent.repository;

import zack.project.domain.task.adapter.repository.ITaskRepository;
import zack.project.domain.task.model.entity.TaskEntity;
import zack.project.infrastructure.event.EventPublisher;
import zack.project.infrastructure.persistent.dao.ITaskDao;
import zack.project.infrastructure.persistent.po.Task;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author A1793
 */
@Repository
public class TaskRepository implements ITaskRepository {
    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher eventPublisher;
    @Override
    public List<TaskEntity> queryNoSendMessageTaskList() {
        List<Task> taskList =  taskDao.queryNoSendMessageTaskList();
        ArrayList<TaskEntity> taskEntities = new ArrayList<>(taskList.size());

        for (Task task : taskList) {
            TaskEntity taskEntity = TaskEntity.builder()
                        .userId(task.getUserId())
                        .topic(task.getTopic())
                        .messageId(task.getMessageId())
                        .message(task.getMessage())
                        .build();
            taskEntities.add(taskEntity);

        }
        return taskEntities;
    }

    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        Task task = new Task();
        task.setUserId(userId);
        task.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(task);
    }

    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        Task task = new Task();
        task.setUserId(userId);
        task.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(task);
    }
}
